package com.Servlet;
import com.DAO.StudentDao;
import com.Student;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/addStudent")
public class AddStudentServlet extends HttpServlet {
    private StudentDao studentDao;

    @Override
    public void init() throws ServletException {
        studentDao = new StudentDao();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 设置字符编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        String studentId = request.getParameter("studentId");
        String name = request.getParameter("name");
        String gender = request.getParameter("gender");
        int age = Integer.parseInt(request.getParameter("age"));
        String email = request.getParameter("email");
        String phone = request.getParameter("phone");

        Student student = new Student();
        student.setStudentId(studentId);
        student.setName(name);
        student.setGender(gender);
        student.setAge(age);
        student.setEmail(email);
        student.setPhone(phone);

        try {
            studentDao.addStudent(student);
        } catch (SQLException e) {
            e.printStackTrace();
            request.setAttribute("errorMessage", "添加学生失败");
            request.getRequestDispatcher("addStudent.jsp").forward(request, response);
            return;
        }

        response.sendRedirect("studentManagement");  // 添加成功后重定向到学生管理页面
    }
}

